Skip to content

Combat 4.2: Cache entity stat snapshots and snapshot projectiles at launch - #385

Merged
Travja merged 5 commits into
devfrom
combat-4.2-stat-snapshots
Nov 18, 2026
Merged

Travja merged 5 commits into
devfrom
combat-4.2-stat-snapshots

Conversation

@Travja

@Travja Travja commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Closes #372. Part of #365.

Every hit read every damage type, defense and item stat from every equipped item of both fighters. EntityStats now keeps a snapshot per entity and rolls ranges at hit time. A projectile that can deal damage records its shooter's snapshot at launch and uses it at impact.

1. What a hit read before (melee, per hit)

What Where Read from How often
Attacker damage types VanillaWrapperListener#onVanillaDamage → EntityStats#getDamageTypes every damage type × every equipped item (DamageAttribute#get, parses item PDC and StatBonus conditions), set/class bonus functions, profile buff (one getOrLoadUser per type), then roll, biome, effects once per hit
Attacker item stats same, getItemStats every global stat type × every item (SimpleStat#get, incl. gem socket lookup), plus the toughness attribute once per hit
Victim defenses same, getDefenseTypes every defense type × every item, plus the armor attribute once per hit
Victim item stats DamageManager#handleDamageModifiers, calculator setup, thornmail dodge, PvP/PvE defense, block damage, block rate, toughness, thornmail: one full item pass each about 7 calls per hit
Enchant protection DamageManager#getEnchantModifier → getEnchantProtectFactor enchant level of every item 2 calls per hit
Codex attributes and buffs scaleValuesWithCore AttributeRegistry / BuffRegistry per damage and defense type per hit, not cached
Attack power, custom-cooldown, attacker ATTACK_DAMAGE attribute, vanilla weapon damage listener / DamageManager entity state / NMS per hit, not cached

DamageCalculator itself reads nothing: it gets plain numbers from DamageManager.

Already cached by EntityStats: inventory (the usable equipped items) and bonuses (set and class bonus functions), both rebuilt in updateAll(). The old comment said damage was "not cached due to broke of range values". The snapshot sits on top of these and is validated against them; it is not a second cache.

After every completed hit, EntityManager also schedules updateAll() for both fighters on the next tick. That matters for the design (see "Why the refresh after a hit is different").

2. Snapshot contents and the maths

Filled in on demand, per entity (StatSnapshot):

  • each damage type's minimum and maximum, summed over the equipment (RANGE_FULL adds every item's min and max before anything is rolled)
  • each defense value, each item stat value, each enchantment protection factor, all before the parts below

Applied at the hit, on every read, and never cached: the roll (Rnd.getDouble(min, max), same single call per type, same order), the biome, active effects (AdjustStatEffect has charges and expires by itself), and an item stat's cap.

Rolled-then-summed question (constraint 2): no stat is rolled per item. Items are summed first and the sum is rolled once, so caching {min, max} keeps the distribution. Proven by a seeded test: the first five rolls for seed 1234 are hard-coded from the base commit's output and match, and cached and uncached sequences are identical.

3. Invalidation

Trigger Handled by
Equipment change (packet detected) EntityManager#onEntityUpdateEquipmentChange → forced updateAll() next tick
Held item EntityManager#onStatsUpdatePlayerHeld → forced updateAll()
Armor equip SetManager#onSetUpdateEquip → updateSets → updateAll()
Join, respawn, spawn onStatsJoin, onStatsUpdatePlayerRespawn, onStatsUpdateMobSpawn → forced
Gear changed with no event (plugin sets armor, offhand swap) refreshAfterHit() compares equipment with the snapshot's own copies and drops it if different. Same one-hit lag as before
Item changed in place (gems, sockets, runes, refine, identify, enchant) same two paths; the snapshot keeps clones, so an aliased stack cannot hide a change
Wear (vanilla damage, Divinity durability) deliberately not a change
Sets SetManager#updateSets → updateAll(); bonus maps also compared by identity after a hit
Class, aspect, class level ClassManager#updateClassData → updateAll()
Profile switch ProfileManager#switchProfile → updateAll(); snapshot also checks the active profile object
Profile buffs added, replaced, removed UserProfile revision counter, compared on each use; BuffCommand calls markBuffsChanged()
Profile buff expiry snapshot validUntil = min(max age, next buff expiry)
Effects added, removed, expired, charges not cached: read at the hit
Codex attributes and buffs (Fabled) not cached: scaleValuesWithCore
Biome not cached: read when rolling
Vanilla ARMOR base / ARMOR_TOUGHNESS attribute no event exists; value used is compared on each read
Death EntityStats#handleDeath (player: dropped; mob: purged)
Quit EntityManager#onStatsQuit → purge
Unload, despawn EntityStats#getAll() sweeps invalid entities every tick (EntityStatsTask); launch snapshots: see section 4
Plugin reload / stat registration Divinity#disable calls ItemStats.clear() (which calls invalidateAllSnapshots), then purges every EntityStats, then ProjectileStats.clear(). So live snapshots go with the purged stats and launch snapshots are cleared; an arrow in flight across a reload is read at impact as before. Registering a stat also invalidates. Covered by a test that reloads the plugin
Anything with no reliable event performance.entity-stats.snapshot-max-age, 20 ticks, 0 turns the cache off

Where there is no reliable event: vanilla attribute changes (potions, other plugins), direct edits to buff sets, level changes made by another plugin, gear set silently by a plugin. Attributes are compared; the rest fall back to the max age. 1 second is a bound on staleness, and a rebuild costs about one old hit, so even a hit every second does no worse than before. Level requirements are decided when the equipment list is rebuilt, as before; that is unchanged.

snapshot-max-age: 0 is a true off switch. Nothing is stored and no items are copied (a test checks StatSnapshot.copyOf is never called); each read works from a throwaway snapshot, which is the old cost.

Why the refresh after a hit is different. Because each hit schedules updateAll() for both fighters, dropping the snapshot there would leave it never alive at the next hit. updateAll() still always drops it (class, profile, set callers). A new refreshAfterHit(), used only by that post-hit path, drops it only if the equipment or bonus maps differ.

Thread safety. Exposure is the same as before, plus one guard. The equipment list is copied under its own lock; each section of a snapshot is filled under the snapshot's lock and never changed afterwards; the bonus list copy cannot throw. Reading buff sets off the main thread (a placeholder read) could throw ConcurrentModificationException before this PR as well (UserProfile#getBuff streams over them), so that is not new. The one new iteration, getNextBuffExpiry, catches it and answers "expires now", so nothing is cached from a read that raced.

4. Projectiles

Carried today as metadata on the projectile: QRPG_PJ_WEAPON (the bow), QRPG_PJ_POWER, QRPG_ARROW_ID/LEVEL. Stats were read at impact from the shooter's current gear with the main hand replaced by the bow.

Now: onProjectileLaunchSnapshot (MONITOR, after all other launch handlers) stores a frozen StatSnapshot with the bow in place of the main hand, the custom arrow's bonus, active effects and the shooter's biome. Impact rolls from it. Weapon and power handling is unchanged.

  • Only damaging projectiles. ProjectileStats#canDealDamage: AbstractArrow (arrows, spectral arrows, tridents) plus the kinds in AmmoAttribute.Type that deal damage (fireball, wither skull, shulker bullet, llama spit). Pearls, snowballs, eggs, bottles and hooks are skipped and read at impact as before. The set comes from AmmoAttribute.Type, which now says which kinds deal damage, rather than a new list.
  • Whose snapshot. It records the shooter's UUID. If the projectile's shooter at impact is someone else (reflected, re-owned), it is ignored and the live read is used, as before this PR.
  • Charges are used at impact. Effects are captured at launch without using their charges (the adjustment is frozen). The hit that lands uses them, once per effect and stat, exactly where the old at-impact read used one. A miss, or a projectile that deals no damage, spends nothing. An effect that has gone by impact is not charged and does not fail.
  • Where they are kept. In a UUID map in ProjectileStats, not metadata, because I believe entity metadata is only cleared when someone removes it (not verified against a server here). ProjectileStats#sweep (every 100 ticks) releases an entry when the projectile is found dead, or cannot be found although the chunk it was last seen in is loaded. A projectile in an unloaded chunk keeps its snapshot. A ten minute upper bound from launch applies to everything, as a safety net.

Intended behaviour changes (two):

  1. Gear swapped or buffs gained after firing no longer affect an arrow in flight.
  2. The biome modifier comes from the shooter's biome at launch, not at impact.

A projectile with no snapshot is read at impact as before.

5. Benchmark

CombatBenchmark (opt-in, -Dcombat.benchmark=true). A geared attacker (3 damage types, 3 stats) hits a victim in 4 armor pieces (3 defenses, 2 stats each) through the real listener. 5 rounds, median, MockBukkit.

before (aed8234) after (final)
burst (hits with nothing between) 51 hits/s 288 hits/s 5.6×
steady (one hit per tick, server tick between) 38 hits/s 117 hits/s 3.1×

Rounds before: burst 54 53 50 49 51, steady 44 38 40 37 33. After: burst 296 276 288 290 269, steady 136 123 117 108 96. (The run before the review fixes gave 281 and 109.) MockBukkit item parsing is far slower than a server, so read these as ratios.

What is deliberately not included

  • Effects, rolls, biome (for live hits), Codex scaling and attack power are not cached (see above).
  • No new hooks for inventory clicks or level-up events: they would call updateAll() far more often, and the existing paths plus the post-hit compare already cover them.
  • No change to the formulas or the arithmetic in DamageCalculator (4.1 changes it); the calculator is untouched.
  • Projectiles launched outside Divinity's launch event are not snapshotted.

Tests

  • All 184 existing tests pass untouched. No characterization test was modified, including the projectile ones: they put the weapon on the arrow by hand without a launch event, so they have no snapshot and still read at impact.
  • 52 new tests: EntityStatSnapshotTest (39: one per trigger above, launch snapshot, release on death, quit, removal, projectile removal, seeded and statistical rolls) and ProjectileLaunchSnapshotTest (13: shooter change via setShooter, two projectiles with different gear, a custom arrow's bonus carried to impact, which projectiles get a snapshot, charges at impact, hold times, reload, off switch).
  • Full suite, real exit code: Tests run: 236, Failures: 0, Errors: 0, Skipped: 2, exit 0. The 2 skipped are the expected trident tests. CI is green on the previous head and runs again on this one.

Break-it checks (each applied, run, reverted)

Break Tests that failed
updateAll() stops dropping the snapshot 5: forced refresh, in-place item, equipment change, held item, set bonus
Post-hit compare always says "same" 3: other item change, silent gear change, set bonus change
Profile buff revision ignored 2
Active profile identity ignored 1
Buff expiry not considered 1
Armor attribute not compared 1
Toughness attribute not compared 1
Projectile damage read at impact 4
Projectile item stats read at impact 1
Roll made when the snapshot is taken 3
Death does not drop player snapshot 1
Quit does not release 1
Mob death does not release 1
Gone entities not swept 1
Projectile snapshots never released 1
invalidateAllSnapshots does nothing 1
Max age ignored 2
Max age 0 does not disable 1
Wear counts as a change 1
Post-hit refresh always drops 3
Launch drops its effects 1
Hit refreshes with a forced update 1
Effects cached in the snapshot 3
Review: shooter check removed at impact 1 (aProjectileThatChangedHands_...)
Review: isShooter always true 1 (same test)
Review: charges used at launch 1 (anArrowThatIsLaunched_butNeverHits_spendsNoCharge)
Review: charges never used at impact 1 (anArrowThatHits_spendsExactlyOneCharge_...)
Review: every projectile gets a snapshot 1 (arrowsGetASnapshot_pearlsAndSnowballsDoNot)
Review: off switch still copies items 2
Review: unloaded chunk releases the snapshot 2
Review: no upper age bound 1
Review: reload leaves launch snapshots 1 (aReload_..., a real plugin reload)

Decisions taken from review

  1. Effect charges on projectiles: captured at launch, used only at impact when the projectile hits. Done.
  2. Max age: stays at 20 ticks. Done.
  3. Launch snapshot cost: only damaging projectiles get one. Done.

🤖 Generated with Claude Code

https://claude.ai/code/session_01FaEyTrj2kNoybQssGMYRpJ

Times hits per second for two situations, hits that follow each other with nothing in between and one hit
per tick, with the same fighters and gear every run. It only runs with -Dcombat.benchmark=true, so it
costs the suite nothing. It exists to put numbers on the stat snapshot change that follows.

Claude-Session: https://claude.ai/code/session_01FaEyTrj2kNoybQssGMYRpJ
Every hit used to read every damage type, defense and item stat from every equipped item of both fighters.
EntityStats now keeps a snapshot per entity: each damage type's minimum and maximum summed over the
equipment, each defense, each item stat and each enchantment protection factor, filled in on demand. The
roll of a damage range, the biome, and active effects are still applied at the hit, so the distribution of
results and the charges of an effect are what they were.

A snapshot is dropped when equipment or held items change, when a set, class or profile asks for a forced
refresh, when profile buffs change or run out, on death, on quit, and when a stats config reload clears
the registries. The refresh a hit asks for on the next tick only drops it if the equipment or bonus maps
differ from what it was built from; wear is not a difference. Vanilla armor and toughness attributes are
compared each time they are used. A maximum age (performance.entity-stats.snapshot-max-age, 20 ticks,
0 turns the cache off) covers changes that nothing announces.

A projectile records a frozen snapshot of its shooter when it is launched, including active effects, and
the hit at impact uses it. Gear swapped or buffs gained after firing no longer affect an arrow in flight.
Projectiles without a snapshot are read at impact, as before.

Claude-Session: https://claude.ai/code/session_01FaEyTrj2kNoybQssGMYRpJ
@Travja Travja added the build:major label Nov 14, 2026 — with Claude
- A launch snapshot records its shooter; a projectile that has changed hands is read live at impact.
- Only projectiles that can deal damage get a snapshot. The set comes from AmmoAttribute.Type plus
  AbstractArrow; pearls, snowballs, eggs, bottles and hooks keep being read at impact.
- Effects are captured at launch without using their charges. The hit that lands uses them, so a miss or a
  projectile that deals no damage spends none.
- snapshot-max-age 0 is a real off switch: no items are copied and nothing is kept.
- The sweep keeps the snapshot of a projectile whose chunk is unloaded and releases it when the projectile
  cannot be found in a loaded chunk or is dead, with a ten minute upper bound.
- A plugin reload clears launch snapshots as well as live ones.
- Reading buff expiry off the main thread can no longer throw.

Claude-Session: https://claude.ai/code/session_01FaEyTrj2kNoybQssGMYRpJ
@Travja
Travja marked this pull request as ready for review November 18, 2026 02:41
@Travja
Travja merged commit ec19379 into dev Nov 18, 2026
2 checks passed
@Travja
Travja deleted the combat-4.2-stat-snapshots branch November 18, 2026 02:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Combat 4.2: Cache entity stat snapshots and snapshot projectiles at launch

2 participants